#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdbool.h>
#include <pthread.h>
//#define count 50
int count = 50;
typedef struct sockaddr* sockaddrp;
int sum_clifd[50];
int cnt;

void* sever(void* arg)
{
	int clifd = *(int*)arg;
	while(1)
	{
		char buf[255] = {};
		int ret = recv(clifd,buf,sizeof(buf),0);
		if(ret < 0)
		{
			perror("recv");
			return NULL;
		}
		if(ret < 0)
		{
			for(int i=0; i<count; i++)
			{
				if(clifd == sum_clifd[i])
				{
					sum_clifd[i] = 0;
					break;
				}
			}
			cnt--;
			sprintf(buf,"已有一个人退出,当前还有%d人",cnt);
			for(int i=0; i<count; i++)
			{
				send(sum_clifd[i],buf,strlen(buf),0);	
			}
			break;
		}
		for(int i=0;i<count;i++)
		{
			if(sum_clifd[i] !=0 && sum_clifd[i] !=  clifd)
			{
			int p = send(sum_clifd[i],buf,strlen(buf),0);
			if(p<0)
			{
				perror("send");
				return NULL;
			}
			}
		}
	}

}

int main(int argc,char* argv[])
{
	int sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(0 > sockfd)
	{
		perror("socket");
		return -1;
	}

	struct sockaddr_in addr = {AF_INET};
	addr.sin_port = htons(atoi(argv[1]));
	addr.sin_addr.s_addr = inet_addr(argv[2]);


	int ret = bind(sockfd,(sockaddrp)&addr,sizeof(addr));

	if(0 > ret)
	{
		perror("bind");
		return -1;
	}
	listen(sockfd,1024);


	while(1)
	{
		struct sockaddr_in src_addr = {};
		socklen_t addr_len = sizeof(src_addr);

		int clifd = accept(sockfd,(sockaddrp)&src_addr,&addr_len);
		cnt++;
		
		
		if(clifd < 0)
		{
			perror("accept");
			return -1;
		}
		
		for(int i = 0; i < count; i++)
		{
			if(sum_clifd[i] == 0)
			{
				sum_clifd[i] = clifd;
				pthread_t tid;
				int pret =pthread_create(&tid,NULL,sever,&clifd);
				break;
			}

			if(cnt == count)
			{
				char buf[255];
				strcpy(buf,"renyijingmanl");
				send(clifd,buf,strlen(buf),0);
				close(clifd);
			}
		
		}
			
	}
		
}
